package com.shengzhe.ostudent.common.filter;

import com.shengzhe.ostudent.common.exception.OsException;
import com.shengzhe.ostudent.utils.jdbc.JDBCUtils;
import com.shengzhe.ostudent.utils.request.RequestLocalHolder;
import com.shengzhe.ostudent.utils.result.E;
import com.shengzhe.ostudent.utils.result.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebFilter("/*")
public class OsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        R r = R.error();
        servletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //把servletRequsst对象变成线程局部变量。
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        RequestLocalHolder.setHttpServletRequest(httpServletRequest);
        // 设置允许哪个域名可以跨域请求到这个Servlet
        // 设置为*表示允许任何域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Token"); // 在这里添加 Token
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true"); // 携带Cookie
        boolean isCatchedException = false;
        try {
            E e = (E) servletRequest.getAttribute("ERR_ENUMS");
            if (e != null) {
                throw new OsException(e);

            }
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (OsException e) {
            isCatchedException = true;
            e.printStackTrace();
            E error = e.getErrEnum();
            r.setSuccess(false);
            r.setCode(error.getCode());
            r.setMessage(error.getMsg());
            r.writeJson(httpServletResponse);
        } catch (Exception exception) {
            isCatchedException = true;
            exception.printStackTrace();
            r.setCode(500);
            r.setMessage(exception.getMessage());
            r.writeJson(httpServletResponse);
        } finally {
            if (isCatchedException) {
                JDBCUtils.rollback();
            }
            //写到最后边
            RequestLocalHolder.clear();
        }


    }

    @Override
    public void destroy() {

    }
}
